package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.cons.GroupType;
import cn.ztydata.teachingsystem.heaven.cons.MsgTemplate;
import cn.ztydata.teachingsystem.heaven.entity.*;
import cn.ztydata.teachingsystem.heaven.service.KpService;
import cn.ztydata.teachingsystem.heaven.service.ResourceService;
import cn.ztydata.teachingsystem.heaven.service.TeacherService;
import cn.ztydata.teachingsystem.heaven.web.dto.*;
import cn.ztydata.teachingsystem.heaven.web.wrapper.HttpSessionProxy;
import cn.ztydata.teachingsystem.util.StringCodeUtil;
import cn.ztydata.teachingsystem.webservice.result.json.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.*;

/**
 * 资源控制器类
 *
 * @author fanruiping
 * @since 2014-12-05
 */
@RequestMapping("/resource")
@Controller
public class ResourceController extends BaseController {
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private KpService kpService;

    @Value("${session.key}")
    private String sessionKey;
    @Value("${file.domain}")
    private String fileDomain;

    /**
     * 资源列表
     * @param specialtyId 专业编号
     * @param typeId 资源类别编号
     * @param mediaType 媒体类型
     * @param status 状态
     * @param search 搜索关键字
     * @param pageNum 页码
     * @param pageSize 每页显示条数
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-10
     */
    @RequestMapping(value = "/list/{specialtyId}/{typeId}/{mediaType}/{status}/{tag}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult list(@PathVariable Long specialtyId,@PathVariable int typeId, @PathVariable Integer mediaType,
                           @PathVariable int status,@PathVariable int tag,
                           @RequestParam(value = "search",required = false, defaultValue = "") String search,
                           @RequestParam(value = "knowledge",required = false, defaultValue = "0") int knowledge,
                           @RequestParam(value = "page",required = false, defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize",required = false, defaultValue = "1") int pageSize,HttpServletRequest request){
        HttpSessionProxy httpSessionProxy = (HttpSessionProxy)request.getSession();

        //搜索关键字转码
        search = StringCodeUtil.urlParamTransCode(search, "utf-8");

        //获取当前用户信息
        User entity = (User)httpSessionProxy.getAttribute(sessionKey);

        Boolean showKnowledge = knowledge == 1 ? true : false;

        Page<Resource> page = resourceService.getList(entity,search,status,specialtyId,typeId,mediaType,pageNum,pageSize,tag,showKnowledge);

        Page<ResourceListDto> pageDto = new Page<>(page.getTotal(),page.getSize(),page.getNum(),mapper.mapList(page.getItems(), ResourceListDto.class));

        log.debug("return resource list");

        return new JsonResultPage<>(pageDto);
    }



    /**
     * 资源类型列表
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-10
     */
    @RequestMapping(value = "/typeList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult typeList(@RequestParam(value = "search",required = false, defaultValue = "") String keyword,
                               @RequestParam(value = "majorId",required = false, defaultValue = "0") Long majorId,
                               @RequestParam(value = "tag",required = false, defaultValue = "0") int tag,HttpServletRequest request){
        HttpSessionProxy httpSessionProxy = (HttpSessionProxy)request.getSession();

        //搜索关键字转码
        keyword = StringCodeUtil.urlParamTransCode(keyword, "utf-8");

        //获取当前用户信息
        User entity = (User)httpSessionProxy.getAttribute(sessionKey);

        List<ResourceType> entities = resourceService.getAllType(keyword, majorId,tag, entity.getUserId(),entity.getRole());

        log.debug("return resource type list");

        return new JsonResultList<>(mapper.mapList(entities, ResourceTypeDto.class));
    }

    /**
     * 资源类型列表
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-10
     */
    @RequestMapping(value = "/typeDownList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult typeDownList(){
        List<ResourceType> entities = resourceService.getAllType();

        log.debug("return resource type list");

        return new JsonResultList<>(mapper.mapList(entities, ResourceTypeDto.class));
    }

    /**
     * 媒体类型资源统计
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-10
     */
    @RequestMapping(value = "/typeStatistical/{specialtyId}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult typeStatistical(@PathVariable int specialtyId){
        //获取统计结果
        Map<String, Object> result = resourceService.getStatisticForMedia(specialtyId, 0);

        log.debug("return mediaType list");

        return new JsonResultData<>(result);
    }

    /**
     * 新增资源
     * @param dto
     * @param request
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-09
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult add(@Valid @RequestBody ResourceInfoDto dto,HttpServletRequest request){
        HttpSessionProxy httpSessionProxy = (HttpSessionProxy)request.getSession();

        //获取当前用户信息
        User entity = (User)httpSessionProxy.getAttribute(sessionKey);

        if(null == entity){
            log.debug("未获取到登录用户信息:null==entity");

            return new JsonResult(false, "未登录");
        }

        dto.setUploaderId(entity.getUserId());

        Resource data = mapper.map(dto, Resource.class);
        data.setUploaderName(entity.getName());

        try{
            resourceService.add(data);

            log.debug("资源新增成功:返回资源编号");

            return new JsonResultId(data.getId());
        }catch (ServiceException ex){
            log.debug("catch ServiceException:return false");

            return new JsonResult(false, ex.getMessage());
        }
    }

    /**
     * 资源明细（0:非群组,1:课程群组,2:专业群组,3:班级群组）
     * @param id
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-09
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    @ResponseBody
   
    public JsonResult detail(@PathVariable("id") long id,
                             @RequestParam(value = "groupType", required = false, defaultValue = "0") int groupType,
                             @RequestParam(value = "groupId", required = false, defaultValue = "0") long groupId){
        Assert.isTrue(id > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源ID"));

        Resource entity = new Resource();

        //如果调用时传进了群组类型、群组ID
        if (groupType >= 0 && groupId > 0){
            entity =  resourceService.getDetail(id, groupType, groupId);
        } else {
            entity = resourceService.getDetail(id, 0, 0);
        }

        if(null == entity){
            log.debug("resource is not exist:null == entity");

            return new JsonResultData<>(false,"资源不存在");
        }

        ResourceInfoDto dto = mapper.map(entity, ResourceInfoDto.class);

        //获取创建者头像
        Teacher teacher = teacherService.getDetail(entity.getUploaderId());

        if(null != teacher){
            log.debug("teacher is exist:null != teacher");

            dto.setPhoto(teacher.getPicture());
            dto.setUploader(teacher.getName());
        }

        log.debug("return resource detail");

        return new JsonResultData<>(mapper.map(entity, ResourceInfoDto.class));
    }

    /**
     * 资源审核
     * @param id
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-10
     */
    @RequestMapping(value = "/edit/{id}/{status}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult edit(@PathVariable long id, @PathVariable int status, HttpServletRequest request){
        HttpSessionProxy httpSessionProxy = (HttpSessionProxy)request.getSession();

        //获取当前用户信息
        User entity = (User)httpSessionProxy.getAttribute(sessionKey);

        if(!Arrays.asList(new Integer[]{1,2}).contains(status)){
            log.debug("status is wrong:!Arrays.asList(new int[]{1,2}).contains(status)");

            return new JsonResult(false,"传递的状态值有误");
        }

        if(1 != resourceService.audit(id,entity.getUserId(),new Timestamp(System.currentTimeMillis()),status)){
            log.debug("audit resource fail:return false");

            return new JsonResult(false, "审核失败");
        }

        log.debug("audit resource success:return true");
        return new JsonResult(true, "审核成功");
    }

    /**
     * 删除指定资源数据
     * @param id 资源编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-23
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult delete(@PathVariable Long id){
        try{
            resourceService.deleteById(id);

            log.debug("delete resource success:return true");

            return new JsonResult(true,"资源删除成功");
        }catch (ServiceException ex){
            log.debug("delete resource fail:catch ServiceException");

            return new JsonResult(false,ex.getMessage());
        }
    }

    /**
     * 热门知识点
     * @param count 数量
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-18
     */
    @RequestMapping(value = "/tagList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult tagList(@RequestParam(value = "pageSize",required = false, defaultValue = "1") Long count){
        List<KnowledgePoint> kps = resourceService.getHotKps(count);

        log.debug("return tag list");

        return new JsonResultList<>(kps);
    }

    /**
     * 新增知识点
     * @param dto 知识点实体
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-24
     */
    @RequestMapping(value = "/tagAdd", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult tagAdd(@RequestBody KpDto dto){
        try{
            KnowledgePoint kp = mapper.map(dto,KnowledgePoint.class);

            kpService.addKp(kp);

            log.debug("return new kp detail");

            return new JsonResultData<>(kp);
        }catch (ServiceException ex){
            log.debug("catch ServiceException:return false");

            return new JsonResult(false,ex.getMessage());
        }
    }

    /**
     * 删除资源知识点(暂不需要)
     * @param resourceId 资源编号
     * @param kpId 知识点编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-16
     */
    @RequestMapping(value = "/delTag/{resourceId}/{kpId}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult delTag(@PathVariable Long resourceId, @PathVariable Long kpId){
        //判断删除资源知识点是否成功
        if(resourceService.deleteKp(resourceId, kpId)){
            log.debug("delete resource kp fail:return true");

            return new JsonResult(true, "资源知识点删除成功");
        }

        log.debug("delete resource kp success:return false");

        return new JsonResult(false, "资源知识点删除失败");
    }

    /**
     * 获取最新资源列表
     * @param count 数据条数
     * @return JsonReulst
     *
     * @author fanruiping
     * @since 2014-12-22
     */
    @RequestMapping(value = "/newList/{count}",method = RequestMethod.GET)
    @ResponseBody
    public JsonNode newList(@PathVariable int count){
        List<Resource> list = resourceService.getNewestList(count);

        Set<Long> uploaderIds = new HashSet<>();
        Set<Long> typeIds = new HashSet<>();

        log.debug("循环最新资源列表获取上传者:Resource entity : list");
        for(Resource entity : list){
            uploaderIds.add(entity.getUploaderId());
        }

        Map<Long,Teacher> teachers = uploaderIds.isEmpty() ? new HashMap<Long,Teacher>() : teacherService.getPictures(uploaderIds);

        ObjectMapper objectMapper = new ObjectMapper();
        ArrayNode nodes = objectMapper.createArrayNode();
        ObjectNode result = objectMapper.createObjectNode();

        log.debug("循环最新资源列表插入上传者名称和头像");
        for (Resource entity : list){
            ObjectNode oneNode = objectMapper.createObjectNode();
            oneNode.put("id", entity.getId());
            oneNode.put("name",entity.getName());
            oneNode.put("suffix",entity.getMediaType());
            oneNode.put("typeName",entity.getTypeName());

            if(!teachers.isEmpty() && teachers.containsKey(entity.getUploaderId())){
                log.debug("可获取到指定教师信息");

                oneNode.put("authorName",teachers.get(entity.getUploaderId()).getName());
                oneNode.put("photo", teachers.get(entity.getUploaderId()).getPicture());
            }

            String uploadDate = entity.getUploadTime().toString();
            oneNode.put("date",uploadDate.substring(0,uploadDate.length()-2));

            nodes.add(oneNode);
        }

        result.put("items",nodes);
        result.put("status", true);
        result.put("message","");

        log.debug("return newest resource list");

        return result;
    }

    /**
     * 下载文件
     * @param resourceId
     * @param response
     * @return HttpServletResponse
     *
     * @author fanruiping
     * @since 2014-12-24
     */
    @RequestMapping(value = "/download/{resourceId}", method = RequestMethod.GET)
    @ResponseBody
    public void download(@PathVariable Long resourceId, HttpServletResponse response, HttpServletRequest request) {
        Attachment info = resourceService.getAttachmentDetail(resourceId);

        if (null != info && info.getDownloadUrl() != null && !info.getDownloadUrl().isEmpty()) {
            log.debug("获取到资源附件或下载地址");

            String path = fileDomain + info.getDownloadUrl();

            resourceService.incrDownloadCnt(resourceId);
            try {
                log.debug("重定向下载资源附件");

                response.sendRedirect(path+"?download=true&filename=" + URLEncoder.encode(info.getFileName(), "utf-8"));
            }catch(IOException ex){
                log.debug("catch IOException");

                log.error(ex.getMessage());
            }
        }
    }

    /**
     * 搜索专业资源（章节）
     *
     * @author chenxin
     * @since 2014/12/18
     */
    @RequestMapping(value = "/relatedList/{pageNum}/{pageSize}/{nodeId}/{typeId}/{mediaType}/{related}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage<ResourceListDto> getListForSearch(@PathVariable int pageNum, @PathVariable int pageSize,
                                                            @PathVariable long nodeId, @PathVariable int typeId,
                                                            @PathVariable int mediaType, @PathVariable int related,
                                                            @RequestParam(required = false) String keyword) {
        //校验参数
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));
        Assert.isTrue(nodeId >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "章节ID"));
        Assert.isTrue(typeId >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源类型"));
        Assert.isTrue(mediaType >= 0 && mediaType <= 4, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "媒体类型"));
        Assert.isTrue(related >= 0 && related <= 1, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "关联知识点标识"));

        //中文转码
        keyword = StringCodeUtil.urlParamTransCode(keyword, StringCodeUtil.UTF8);

        //获取课程资源
        Page<Resource> page = resourceService.getListForSearch(pageNum, pageSize, 0, nodeId, typeId,
                mediaType, keyword, related > 0, false);
        //映射到dto类
        Page<ResourceListDto> result = new Page<>(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), ResourceListDto.class));

        log.debug("获取专业资源列表");
        return new JsonResultPage<>(result);
    }

    /**
     * 收藏资源
     * @param id 资源编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-02-09
     */
    @RequestMapping(value = "/collect/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult collect(@PathVariable int id,HttpServletRequest request){
        HttpSessionProxy httpSessionProxy = (HttpSessionProxy)request.getSession();

        //获取当前用户信息
        User entity = (User)httpSessionProxy.getAttribute(sessionKey);

        //判断资源是否已被收藏
        if(resourceService.isCollected(entity.getUserId(), id)){
            log.debug("资源已被收藏:resourceService.isCollected(entity.getUserId(), id)");

            return new JsonResult(false, "该资源已被收藏");
        }

        //添加收藏
        if(resourceService.collect(entity.getUserId(),id)){
            log.debug("资源收藏成功:resourceService.collect(entity.getUserId(),id)");

            return new JsonResult(true,"收藏成功");
        }

        log.debug("资源收藏失败");

        return new JsonResult(false,"收藏失败");
    }

    /**
     * 取消收藏指定资源
     * @param resourceId 资源编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-05-08
     */
    @RequestMapping(value = "/cancelCollect/{resourceId}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult cancelCollect(@PathVariable Long resourceId){
        //校验参数
        Assert.isTrue(resourceId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源编号"));

        //取消收藏
        if(resourceService.cancelCollect(resourceId)){
            return new JsonResult(true,"取消收藏成功");
        }

        return new JsonResult(false,"取消收藏失败");
    }

    /**
     * 获取习题的推荐列表
     *
     * @author chenxin
     * @since 2015/2/9
     */
    @RequestMapping(value = "/searchByKps/{pageNum}/{pageSize}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getListByKps(@PathVariable int pageNum, @PathVariable int pageSize, @RequestParam("knowledge") List<Long> kpIds) {
        //校验参数
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));

        if (kpIds == null || kpIds.isEmpty()) {
            log.debug("kpIds is empty or null");

            return new JsonResultPage<>(true, "暂无推荐的资源");
        }

        //根据知识点ID集合获取资源推荐列表
        Page<Resource> page = resourceService.getListByKps(pageNum, pageSize, kpIds);

        //映射结果到Dto
        Page<ResourceListDto> result = new Page<>(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), ResourceListDto.class));

        log.debug("return resource list by kpIds");

        return new JsonResultPage<>(result);
    }


    /**
     * 获取群组资源列表
     *
     * @param groupType 群组类型（0非群组1课程群组2专业群组3班级群组）
     * @param groupId 群组ID
     * @param tag 标记（0全部1我的2收藏）
     * @param typeId 资源类型ID
     * @param keyword 关键字
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return JsonResultList
     * @author lyj
     * @since 2015-3-31
     */
    @RequestMapping(value = "/lessonGroup", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage getGroupResource(@RequestParam("groupType") int groupType,
                                           @RequestParam("groupId") long groupId,
                                           @RequestParam("tag") int tag,
                                           @RequestParam("type") long typeId,
                                           @RequestParam(value = "keyword", required = false, defaultValue = "") String keyword,
                                           @RequestParam("page") int pageNum,
                                           @RequestParam("pageSize") int pageSize,
                                           HttpServletRequest request) {
        Assert.isTrue(groupType >= 0 && groupType <= 3, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组类型"));
        Assert.isTrue(groupId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组ID"));
        Assert.isTrue(tag >= 0 && tag < 3, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "tag标记"));
        Assert.isTrue(typeId >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源类型"));
        Assert.notNull(keyword, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "关键字"));
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "当前页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));

        keyword = StringCodeUtil.urlParamTransCode(keyword, "utf-8"); //汉字转码

        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        Page page = resourceService.getGroupResource(groupType, groupId, tag, typeId, keyword, pageNum, pageSize, userInfo);

        log.debug("获取群组资源列表");
        return new JsonResultPage(new Page(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), ResourceInfoDto.class)));
    }


    /**
     * 推荐资源
     *
     * @param mapCommend
     * @return JsonResult
     * @author lyj
     * @since 2015-3-31
     */
    @RequestMapping(value = "/lessonGroupRecommend", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult recommend(@RequestBody Map<String, Object> mapCommend){
        Assert.isTrue((int)mapCommend.get("id") > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源ID"));
        Assert.isTrue((int)mapCommend.get("pushed") == 1, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "推荐标识"));
        Assert.isTrue((int)mapCommend.get("groupType") > 0 && (int)mapCommend.get("groupType") < 4, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组类型"));
        Assert.isTrue((int)mapCommend.get("groupId") > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "推荐标识"));

        resourceService.recommend(mapCommend);

        log.debug("推荐资源");
        return new JsonResult(true, "推荐成功！");
    }


    /**
     * 收藏资源
     *
     * @param rscId 资源ID
     * @param best 是否收藏资源(0取消收藏 1收藏)
     * @return JsonResult
     * @author lyj
     * @since 2015-3-31
     */
    @RequestMapping(value = "/lessonGroupBest/{id}/{best}/{groupType}/{groupId}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult collection(@PathVariable("id") long rscId,
                                 @PathVariable("best") int best,
                                 @PathVariable("groupId") long groupId,
                                 @PathVariable("groupType") int groupType){
        Assert.isTrue(rscId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源ID"));
        Assert.isTrue(best == 0 || best == 1, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源状态"));
        Assert.isTrue(groupId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组ID"));
        Assert.isTrue(groupType >= 0 && groupType < 4, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组类型"));

        resourceService.collection(rscId, best, groupId, groupType);

        log.debug("收藏资源");
        return new JsonResult(true, "操作成功！");
    }


    /**
     * 获取热门资源列表
     *
     * @param groupType 群组类型
     * @param groupId 群组ID
     * @param count 条数
     * @return JsonResultList
     * @author lyj
     * @since 2015-4-1
     */
    @RequestMapping(value = "/lessonGroupHotList/{groupType}/{groupId}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultList getHotList(@PathVariable("groupType") int groupType,
                                     @PathVariable("groupId") long groupId,
                                     @RequestParam("pageSize") int count,
                                     HttpServletRequest request){
        Assert.isTrue(groupType >= GroupType.NOT_GROUP && groupType <= GroupType.CLASS_GROUP, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组类型"));
        Assert.isTrue(groupId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组ID"));
        Assert.isTrue(count > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "条数"));

        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        log.debug("获取热门资源列表");
        return new JsonResultList(mapper.mapList(resourceService.getHotRsc(groupType, groupId, count, userInfo), ResourceInfoDto.class));
    }


    /**
     * 增加课程群组资源
     *
     * @param resourceGroupDto 资源实体
     * @return JsonResult
     * @author lyj
     * @since 2015-4-3
     */
    @RequestMapping(value = "/groupAdd ", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addGroupResource(@Valid @RequestBody ResourceGroupDto resourceGroupDto,
                                       HttpServletRequest request) {

        Resource data = mapper.map(resourceGroupDto, Resource.class);

        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        //新增资源并返回资源ID
        resourceService.addGroupResource(data, userInfo);

        log.debug("增加课程群组资源");
        return new JsonResultId(data.getId());

    }


	/**
     * 全部资源列表
     * @param specialtyId
     * @param pageNum
     * @param pageSize
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-03-31
     */
    @ResponseBody
    @RequestMapping(value = "/praxisAllList/{specialtyId}/{pageNum}/{pageSize}", method = RequestMethod.GET)
    public JsonResult praxisAllList(@PathVariable Long specialtyId,@PathVariable int pageNum,@PathVariable int pageSize){
        Page<Resource> page = resourceService.getRecommendForTest(specialtyId,pageNum,pageSize);

        Page<ResourceListDto> listDtoPage = new Page<>(page.getTotal(),pageSize,pageNum,mapper.mapList(page.getItems(),ResourceListDto.class));

        return new JsonResultPage<>(listDtoPage);
	}

	/**
     * 线下作业-推荐资源列表
     * 
     * @param specId 专业ID
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @param kpIds 知识点ID集合
     * @return json
     * 
     * @author cx
     * @since 2015/4/6
     */
    @RequestMapping(value = "/praxisRecommendList/{specId}/{pageNum}/{pageSize}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getResourcesForOfflineTest(@PathVariable long specId, @PathVariable int pageNum, @PathVariable int pageSize, @RequestParam("knowledge") List<Long> kpIds) {
        //校验参数
        Assert.isTrue(specId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "专业ID"));
        Assert.isTrue(pageNum > 0 && pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "页码参数"));

        if (kpIds == null || kpIds.isEmpty()) {
            log.debug("知识点ID集合为空:kpIds == null || kpIds.isEmpty()");
            return new JsonResultPage<>(true, "暂无推荐资源");
        }

        //获取资源分页列表
        Page<Resource> resourcesPage = resourceService.getListForTestCreate(pageNum, pageSize, specId, kpIds);

        //转为dto
        Page<ResourceListDto> result = new Page<>(resourcesPage.getTotal(), pageSize, pageNum, mapper.mapList(resourcesPage.getItems(), ResourceListDto.class));

        log.debug("线下作业-推荐资源列表");
        return new JsonResultPage<>(result);
    }



    /**
     * 我的资源统计图（学生）
     * @param type
     * @param groupId
     * @return JsonResultData
     * @author lyj
     * @since 2015-4-14
     */
    @RequestMapping(value = "/studentResourceChart", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultData getStudentResourceChart(@RequestParam("type") int type,
                                                  @RequestParam("groupId") long groupId,
                                                  HttpServletRequest request) {
        Assert.isTrue(groupId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组ＩＤ"));

        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        //获取统计结果
        Map<String, Object> result = resourceService.getStudentResourceChart(type, groupId, userInfo);

        log.debug("我的资源统计图");
        return new JsonResultData<>(result);
    }

    /**
     * 资源类型列表
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-05-06
     */
    @RequestMapping(value = "/myTypeStatistics", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult myTypeStatistics(@RequestParam(value = "search",required = false, defaultValue = "") String keyword,
                               @RequestParam(value = "id",required = false, defaultValue = "0") Long id,
                               @RequestParam(value = "tag",required = false, defaultValue = "0") int tag,
                               @RequestParam(value = "type",required = false, defaultValue = "0") int type){
        //数据验证
        Assert.isTrue(id >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR,"群组或专业编号"));
        Assert.isTrue(tag == 0 || tag == 1, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR,"标记"));
        Assert.isTrue(type >= 0 && type <= 4, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR,"群组类型"));

        //搜索关键字转码
        keyword = StringCodeUtil.urlParamTransCode(keyword, "utf-8");

        List<Map<String, Object>> entities = resourceService.getTypeStatisticsForMine(id,type,tag,keyword);

        return new JsonResultList<>(mapper.mapList(entities, ResourceTypeDto.class));
    }

    /**
     * 我（创建或收藏）的资源列表
     * @param groupId 群组编号(0：全部)
     * @param groupType 群组类型(0：专业、1：课程、2：专业群组、3：班级)
     * @param mediaType 媒体类型0：全部
     * @param status 状态(0：所有、1：未审核、2：通过、3：忽略、4：未完成、5：无效)
     * @param typeId 资源类型0：全部
     * @param search 搜索关键字
     * @param tag 标记(0：我的、1：收藏)
     * @param pageNum 页码
     * @param pageSize 分页
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-05-06
     */
    @RequestMapping(value = "/myList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult myList(@RequestParam(value = "id", defaultValue = "0") Long groupId,
                           @RequestParam(value = "tabType", defaultValue = "0") int groupType,
                           @RequestParam(value = "mediaType",defaultValue = "0") int mediaType,
                           @RequestParam(value = "resourceStatus", defaultValue = "0") int status,
                           @RequestParam(value = "resourceType", defaultValue = "0") int typeId,
                           @RequestParam(value = "search",required = false, defaultValue = "") String search,
                           @RequestParam(value = "tag", defaultValue = "0") int tag,
                           @RequestParam(value = "page",required = false, defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize",required = false, defaultValue = "1") int pageSize){
        //数据验证
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR,"当前页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR,"每页条数"));

        //搜索关键字转码
        search = StringCodeUtil.urlParamTransCode(search, "utf-8");

        Page<Resource> page = resourceService.getMyResourceList(tag,groupId,groupType,mediaType,status,typeId,search,pageNum,pageSize);

        Page<ResourceListDto> pageDto = new Page<>(page.getTotal(),page.getSize(),page.getNum(),mapper.mapList(page.getItems(), ResourceListDto.class));

        return new JsonResultPage<>(pageDto);
    }
}
